package com.example.springboottest.processor;

import com.example.springboottest.annotation.MyAnnotationClass;
import com.example.springboottest.annotation.MyAnnotationMethod;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
public class MyPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        Object instance = null;
        if(bean.getClass().isAnnotationPresent(MyAnnotationClass.class)){
            MyAnnotationClass annotation = bean.getClass().getAnnotation(MyAnnotationClass.class);
            if(annotation.value()){
                return bean;
            }
            Method[] methods = bean.getClass().getDeclaredMethods();

            for (Method method : methods) {
                if(method.isAnnotationPresent(MyAnnotationMethod.class)) {
                    if("jiajia".equals(method.getAnnotation(MyAnnotationMethod.class).value())) {
                        instance  = getInstance(bean.getClass());//代理类
                    }else{
                        instance = bean;
                    }
                }
            }
        }
        return instance;
    }

    private Object getInstance(Class<?> clazz) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                System.out.println("准备开始。。。");
                Object o1 = methodProxy.invokeSuper(o, objects);
                System.out.println("准备之后。。。");
                return o1;
            }
        });
        return enhancer.create();
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }
}
